import { Hono } from 'hono'
import { SecurityService } from '@/services/securityService'
import { asyncHandler, NotFoundError, AuthorizationError, ValidationError } from '@/middleware/errorHandler'
import { requireAuth, requireRole } from '@/middleware/auth'
import { prisma } from '@/lib/database'

const security = new Hono()
const securityService = new SecurityService()

// 手动触发插件版本安全扫描 (管理员功能)
security.post('/scan/:versionId',
  requireAuth,
  requireRole(['admin']),
  asyncHandler(async (c) => {
    const versionId = c.req.param('versionId')

    // 验证插件版本是否存在
    const version = await prisma.pluginVersion.findUnique({
      where: { id: versionId },
      include: {
        plugin: {
          select: { name: true, displayName: true }
        }
      }
    })

    if (!version) {
      throw new NotFoundError('Plugin version not found')
    }

    // 执行安全扫描
    const result = await securityService.scanPlugin(versionId)

    return c.json({
      success: true,
      data: { 
        scanResult: result,
        plugin: version.plugin,
        version: version.version
      },
      message: 'Security scan completed'
    })
  })
)

// 获取插件版本的安全扫描结果
security.get('/scan/:versionId',
  requireAuth,
  asyncHandler(async (c) => {
    const versionId = c.req.param('versionId')
    const userId = c.get('userId')
    const userRole = c.get('userRole')

    // 获取插件版本信息
    const version = await prisma.pluginVersion.findUnique({
      where: { id: versionId },
      include: {
        plugin: {
          select: { 
            name: true, 
            displayName: true, 
            developerId: true 
          }
        }
      }
    })

    if (!version) {
      throw new NotFoundError('Plugin version not found')
    }

    // 权限检查：只有插件开发者或管理员可以查看详细的安全扫描结果
    if (userRole !== 'admin' && version.plugin.developerId !== userId) {
      throw new AuthorizationError('Access denied')
    }

    return c.json({
      success: true,
      data: {
        versionId: version.id,
        version: version.version,
        plugin: version.plugin,
        securityScanStatus: version.securityScanStatus,
        securityScanResult: version.securityScanResult,
        scannedAt: version.updatedAt
      },
      message: 'Security scan result retrieved'
    })
  })
)

// 批量扫描待处理的插件 (管理员功能)
security.post('/scan-pending',
  requireAuth,
  requireRole(['admin']),
  asyncHandler(async (c) => {
    await securityService.scanPendingPlugins()

    return c.json({
      success: true,
      message: 'Pending security scans initiated'
    })
  })
)

// 获取安全扫描统计信息 (管理员功能)
security.get('/stats',
  requireAuth,
  requireRole(['admin']),
  asyncHandler(async (c) => {
    const [
      totalScans,
      passedScans,
      failedScans,
      pendingScans,
      recentScans
    ] = await Promise.all([
      prisma.pluginVersion.count({
        where: {
          OR: [
            { securityScanStatus: 'passed' },
            { securityScanStatus: 'failed' },
            { securityScanStatus: 'pending' }
          ]
        }
      }),
      prisma.pluginVersion.count({
        where: {
          securityScanStatus: 'passed'
        }
      }),
      prisma.pluginVersion.count({
        where: {
          securityScanStatus: 'failed'
        }
      }),
      prisma.pluginVersion.count({
        where: {
          securityScanStatus: 'pending'
        }
      }),
      prisma.pluginVersion.findMany({
        where: {
          OR: [
            { securityScanStatus: 'passed' },
            { securityScanStatus: 'failed' },
            { securityScanStatus: 'pending' }
          ]
        },
        include: {
          plugin: {
            select: { name: true, displayName: true }
          }
        },
        orderBy: { updatedAt: 'desc' },
        take: 10
      })
    ])

    return c.json({
      success: true,
      data: {
        stats: {
          total: totalScans,
          passed: passedScans,
          failed: failedScans,
          pending: pendingScans,
          passRate: totalScans > 0 ? Math.round((passedScans / totalScans) * 100) : 0
        },
        recentScans: recentScans.map(scan => ({
          id: scan.id,
          version: scan.version,
          plugin: scan.plugin,
          status: scan.securityScanStatus,
          scannedAt: scan.updatedAt
        }))
      },
      message: 'Security scan statistics retrieved'
    })
  })
)

// 获取插件版本的详细安全报告
security.get('/report/:versionId',
  requireAuth,
  requireRole(['admin']),
  asyncHandler(async (c) => {
    const { versionId } = c.req.param()

    // 获取插件版本信息
    const pluginVersion = await prisma.pluginVersion.findUnique({
      where: { id: versionId },
      include: {
        plugin: {
          select: { name: true, displayName: true }
        }
      }
    })

    if (!pluginVersion) {
      throw new NotFoundError('Plugin version not found')
    }

    // 如果还没有扫描结果，返回提示
    if (!pluginVersion.securityScanResult) {
      return c.json({
        success: false,
        message: 'No security scan results available. Please run a security scan first.',
        data: {
          plugin: pluginVersion.plugin,
          version: pluginVersion.version,
          scanStatus: pluginVersion.securityScanStatus
        }
      })
    }

    const scanResult = pluginVersion.securityScanResult as any

    return c.json({
      success: true,
      data: {
        plugin: pluginVersion.plugin,
        version: pluginVersion.version,
        scanStatus: pluginVersion.securityScanStatus,
        scanResult: {
          passed: scanResult.passed,
          score: scanResult.score,
          issues: scanResult.issues,
          summary: {
            totalIssues: scanResult.issues?.length || 0,
            criticalIssues: scanResult.issues?.filter((i: any) => i.severity === 'critical').length || 0,
            highIssues: scanResult.issues?.filter((i: any) => i.severity === 'high').length || 0,
            mediumIssues: scanResult.issues?.filter((i: any) => i.severity === 'medium').length || 0,
            lowIssues: scanResult.issues?.filter((i: any) => i.severity === 'low').length || 0
          }
        },
        scannedAt: pluginVersion.updatedAt
      },
      message: 'Security report retrieved successfully'
    })
  })
)

// 获取安全问题列表 (管理员功能)
security.get('/issues',
  requireAuth,
  requireRole(['admin']),
  asyncHandler(async (c) => {
    const severity = c.req.query('severity') // 'critical', 'high', 'medium', 'low'
    const page = parseInt(c.req.query('page') || '1')
    const limit = parseInt(c.req.query('limit') || '20')
    const offset = (page - 1) * limit

    // 获取有安全问题的插件版本
    const versions = await prisma.pluginVersion.findMany({
      where: {
        securityScanStatus: 'failed',
        securityScanResult: { not: null as any }
      },
      include: {
        plugin: {
          select: { 
            name: true, 
            displayName: true,
            developer: {
              select: { username: true, displayName: true }
            }
          }
        }
      },
      orderBy: { updatedAt: 'desc' },
      skip: offset,
      take: limit
    })

    const total = await prisma.pluginVersion.count({
      where: {
        securityScanStatus: 'failed',
        securityScanResult: { not: null as any }
      }
    })

    // 过滤和格式化安全问题
    const issues = versions.flatMap(version => {
      const scanResult = version.securityScanResult as any
      if (!scanResult?.issues) return []

      return scanResult.issues
        .filter((issue: any) => !severity || issue.severity === severity)
        .map((issue: any) => ({
          ...issue,
          versionId: version.id,
          version: version.version,
          pluginId: version.pluginId,
          scannedAt: version.updatedAt
        }))
    })

    return c.json({
      success: true,
      data: {
        issues,
        pagination: {
          page,
          limit,
          total,
          totalPages: Math.ceil(total / limit)
        }
      },
      message: 'Security issues retrieved'
    })
  })
)

// 批量检查依赖安全性
security.post('/check-dependencies',
  requireAuth,
  requireRole(['admin']),
  asyncHandler(async (c) => {
    const { dependencies } = await c.req.json()

    if (!dependencies || typeof dependencies !== 'object') {
      throw new ValidationError('Dependencies object is required')
    }

    // const securityService = new SecurityService()
    const vulnerabilityService = new (await import('@/services/vulnerabilityService')).VulnerabilityService()

    const results = []

    for (const [packageName, version] of Object.entries(dependencies)) {
      const vulnerabilities = vulnerabilityService.checkVulnerabilities(packageName, version as string)
      const isMalicious = vulnerabilityService.isMaliciousPackage(packageName)

      results.push({
        package: packageName,
        version: version as string,
        isMalicious,
        vulnerabilities: vulnerabilities.map(vuln => ({
          id: vuln.id,
          severity: vuln.severity,
          title: vuln.title,
          description: vuln.description,
          cve: vuln.cve,
          patchedVersions: vuln.patchedVersions
        })),
        riskScore: vulnerabilityService.calculatePackageRisk(
          { name: packageName, version: version as string },
          vulnerabilities
        )
      })
    }

    // 统计信息
    const stats = {
      totalPackages: results.length,
      maliciousPackages: results.filter(r => r.isMalicious).length,
      vulnerablePackages: results.filter(r => r.vulnerabilities.length > 0).length,
      highRiskPackages: results.filter(r => r.riskScore >= 50).length,
      averageRiskScore: results.reduce((sum, r) => sum + r.riskScore, 0) / results.length
    }

    return c.json({
      success: true,
      data: {
        results,
        stats
      },
      message: 'Dependency security check completed'
    })
  })
)

export default security
